from rest_framework import serializers
from .models import User
from rest_framework_jwt.settings import api_settings
from . import service
import re
import logging
log = logging.getLogger("django")

class UserModelSerializer(serializers.ModelSerializer):
    token = serializers.CharField(read_only=True, label="jwt的token字符串")
    password_confirm = serializers.CharField(label='确认密码', write_only=True)

    class Meta:
        model = User
        fields = ["mobile", "username", "password", "password_confirm","token", "id"]
        extra_kwargs = {
            "id":{
                "read_only":True,
            },
            "username": {
                "read_only": True,
            },
            "password":{
                "write_only":True,
            },
            "mobile": {
                "write_only": True,
            }
        }

    def validate(self, data):
        # 接受数据
        # username = data.get("username")
        mobile = data.get("mobile")
        password = data.get("password")
        password_confirm = data.get("password_confirm")

        # 验证手机格式
        if not re.match("^1[3-9]\d{9}$",mobile):
            raise serializers.ValidationError("手机号格式不正确!")

        # 验证手机是否注册了
        try:
            User.objects.get(mobile=mobile)
            raise serializers.ValidationError("手机号码已经被注册！")
        except:
            pass

        # # 验证帐号是否注册了
        # total = User.objects.count()
        # if total >= 2:
        #     raise serializers.ValidationError({"username":"已注册过用户，无法继续注册"})
        # # 验证帐号长度
        # if len(username) < 6 or len(username) > 20:
        #     raise serializers.ValidationError({"username":"帐号必须保持在6-20位字符长度之间"})


        # 验证密码长度
        if len(password) < 6 or len(password) > 20:
            raise serializers.ValidationError({"password":"密码必须保持在6-20位字符长度之间!"})

        if password != password_confirm:
            raise serializers.ValidationError({"password":"两次密码不一致，请重新输入"})

        # 必须返回数据
        return data

    def create(self, validated_data):
        # username = validated_data.get("username")
        mobile = validated_data.get("mobile")
        password = validated_data.get("password")
        # enable_password = service.encryption(password)
        try:
            user = User.objects.create_user(
                username=mobile,
                mobile=mobile,
                password=password,
                # tel="请联系客服电话:15768816912修改密码",
                tel="请联系管理员修改密码:15768816912",
                # enable_password=enable_password
            )
        except:
            # log.error("创建用户失败！username=%s" % username)
            log.error("创建用户失败！mobile=%s" % mobile)
            raise serializers.ValidationError({"username":"注册用户失败！请联系客服工作人员！"})

        # 注册成功以后，默认当前用户为登录状态，返回返回登录的jwt token值
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        user.token = jwt_encode_handler(payload)

        return user
